package com.heima.wemedia.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult login(WmLoginDto dto) {
       //TODO


        //从数据库核对前端传过来的账号，并返回该用户
        WmUser wmUser = wmUserMapper.selectOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //如果从数据库查询为空，则直接return
        if (ObjectUtil.isEmpty(wmUser)){
            log.error("[用户查询]错误");
            return ResponseResult.errorResult(2,"账号不存在");
        }
        //验证用户的密码
        String password = dto.getPassword();
        boolean checkpw = BCrypt.checkpw(password, wmUser.getPassword());
        if (checkpw){
            //用户验证成功
            //生成jwt令牌返回给前端
            String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getApUserId()));


            return null;
        }else {
            //用户验证失败
            log.error("[密码错误]");
            return ResponseResult.errorResult(2,"密码错误");
        }
    }
}